<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时监控</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        h1, h2, h3 {
            color: #333;
        }
        h2 {
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-top: 30px;
        }
        h3 {
            margin-top: 20px;
            color: #555;
        }
        .status-panel {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }
        .status-card {
            padding: 20px;
            border-radius: 5px;
            background-color: #f9f9f9;
            text-align: center;
            border: 1px solid #eee;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            transition: all 0.3s;
        }
        .status-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .status-card h3 {
            margin: 0;
            color: #555;
            font-size: 16px;
        }
        .status-card .value {
            font-size: 28px;
            font-weight: bold;
            color: #4CAF50;
            margin: 15px 0;
        }
        .control-panel {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }
        .control-btn {
            padding: 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        .control-btn.active {
            background-color: #4CAF50;
            color: white;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }
        .control-btn.exiting {
            background-color: #FFC107;
            color: white;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }
        .control-btn.inactive {
            background-color: #f5f5f5;
            color: #666;
            border: 1px solid #ddd;
        }
        .control-btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
        }
        .section-title {
            margin-top: 30px;
            margin-bottom: 15px;
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .bluetooth-devices {
            margin-top: 20px;
        }
        .device-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            margin-bottom: 20px;
        }
        .device-table th, .device-table td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .device-table th {
            background-color: #f2f2f2;
        }
        .device-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .device-table tr:hover {
            background-color: #f0f0f0;
        }
        .signal-strength {
            display: inline-block;
            width: 50px;
            height: 10px;
            background-color: #eee;
            position: relative;
            margin-top: 5px;
        }
        .signal-bar {
            height: 100%;
            background-color: #4CAF50;
            position: absolute;
            left: 0;
        }
        .refresh-btn {
            padding: 8px 12px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            font-size: 14px;
        }
        .refresh-btn:hover {
            background-color: #0b7dda;
        }
        .last-update {
            font-size: 0.8em;
            color: #555;
            margin-top: 5px;
        }
        #message {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px;
            border-radius: 5px;
            color: white;
            display: none;
            z-index: 1000;
        }
        #message.success {
            background-color: #4CAF50;
        }
        #message.error {
            background-color: #f44336;
        }
        .navbar {
            background-color: #333;
            overflow: hidden;
            margin-bottom: 20px;
        }
        .navbar a {
            float: left;
            display: block;
            color: white;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
        }
        .navbar a:hover {
            background-color: #ddd;
            color: black;
        }
        .navbar a.active {
            background-color: #4CAF50;
        }
        .header-actions {
            margin: 20px 0;
            text-align: right;
        }
        .header-actions button {
            padding: 8px 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            font-size: 14px;
        }
        .header-actions button:hover {
            background-color: #45a049;
        }
        .header-actions button:last-child {
            background-color: #f44336;
        }
        .header-actions button:last-child:hover {
            background-color: #d32f2f;
        }
        .mock-device {
            background-color: #f0f0f0;
        }
        .mock-device-name {
            font-weight: bold;
        }
        .mode-buttons {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin: 20px 0;
        }
        .mode-button {
            padding: 15px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            text-align: center;
            transition: all 0.3s ease;
            background-color: #e9ecef;
            color: #495057;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            border: 1px solid #dee2e6;
        }
        .mode-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .mode-button.active {
            background-color: #4CAF50;
            color: white;
            border-color: transparent;
        }
        .mode-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .mode-button.loading {
            position: relative;
            color: transparent;
        }
        .mode-button.loading::after {
            content: "";
            position: absolute;
            width: 16px;
            height: 16px;
            top: 50%;
            left: 50%;
            margin-top: -8px;
            margin-left: -8px;
            border-radius: 50%;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top-color: #fff;
            animation: spin 1s infinite linear;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        #autoModeBtn {
            background-color: #e3f2fd;
            border-color: #90caf9;
            color: #1976d2;
        }
        #autoModeBtn:hover {
            background-color: #1976d2;
            color: white;
            border-color: transparent;
        }
        #autoModeBtn.active {
            background-color: #1976d2;
            color: white;
            border-color: transparent;
        }
        #autoModeBtn.exiting {
            background-color: #FFC107;
            color: white;
            border-color: transparent;
        }
        #autoModeBtn.waiting {
            background-color: #FFC107;
            color: white;
            border-color: transparent;
            cursor: not-allowed;
        }
        #autoModeBtn.error {
            background-color: #f44336;
            color: white;
            border-color: transparent;
        }
        #forceHeatingMode {
            background-color: #fff3e0;
            border-color: #ffcc80;
            color: #f57c00;
        }
        #forceHeatingMode:hover, #forceHeatingMode.active {
            background-color: #f57c00;
            color: white;
            border-color: transparent;
        }
        #forceCoolingMode {
            background-color: #e8f5e9;
            border-color: #a5d6a7;
            color: #388e3c;
        }
        #forceCoolingMode:hover, #forceCoolingMode.active {
            background-color: #388e3c;
            color: white;
            border-color: transparent;
        }
        .mode-button.waiting {
            background-color: #FFC107;
            color: white;
            cursor: not-allowed;
        }
        .mode-button.error {
            background-color: #f44336;
            color: white;
        }
    </style>
</head>
<body>
    <div class="navbar">
        <a href="/welcome.html">首页</a>
        <a href="/monitor.html" class="active">监控</a>
        <a href="/config.html" id="configLink" style="display: none;">配置</a>
        <a href="/log.html">日志</a>
        <a href="/music.html">音乐</a>
    </div>
    
    <div class="container">
        <h1>实时监控</h1>
        
        <div class="last-update">
            最后更新时间: <span id="statusLastUpdateTime">--</span>
        </div>
        
        <div class="header-actions">
            <button onclick="updateStatus()">刷新状态</button>
            <button onclick="logout()">退出登录</button>
        </div>
        
        <div id="message"></div>
        
        <div class="status-panel">
            <div class="status-card">
                <h3>当前温度</h3>
                <div id="currentTemp" class="value">--</div>
                <div>℃</div>
            </div>
            <div class="status-card">
                <h3>当前功率</h3>
                <div id="currentPower" class="value">--</div>
                <div>%</div>
            </div>
            <div class="status-card">
                <h3>加热状态</h3>
                <div id="heatingStatus" class="value">--</div>
            </div>
            <div class="status-card">
                <h3>冷却状态</h3>
                <div id="coolingStatus" class="value">--</div>
            </div>
            <div class="status-card">
                <h3>工作时长</h3>
                <div id="workingTime" class="value">--/--</div>
                <div>分钟</div>
            </div>
        </div>
        
        <div class="mode-buttons">
            <button id="autoModeBtn" class="mode-button" onclick="handleAutoMode()">自动模式 [已停止]</button>
            <button id="forceHeatingMode" class="mode-button" onclick="switchMode('heating')">强制加热 [已停止]</button>
            <button id="forceCoolingMode" class="mode-button" onclick="switchMode('cooling')">强制冷却 [已停止]</button>
        </div>

        <!-- 蓝牙设备信息部分 -->
        <h2 class="section-title">蓝牙设备信息</h2>
        
        <!-- 烟感设备部分 -->
        <h3>烟感设备</h3>
        <div class="bluetooth-devices">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>已发现 <span id="smokeDeviceCount">0</span> 个烟感设备</div>
                <button class="refresh-btn" onclick="updateSmokeDevices()">刷新烟感设备</button>
            </div>
            <div class="last-update">最后更新时间: <span id="smokeLastUpdateTime">--</span></div>
            <table class="device-table">
                <thead>
                    <tr>
                        <th>设备名称</th>
                        <th>MAC地址</th>
                        <th>信号强度 (RSSI)</th>
                        <th>发射功率 (TX Power)</th>
                        <th>最后发现时间</th>
                    </tr>
                </thead>
                <tbody id="smokeDeviceTableBody">
                    <!-- 设备列表将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
        
        <!-- 模拟人员设备部分 -->
        <h3>模拟人员设备</h3>
        <div class="bluetooth-devices">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>已发现 <span id="personnelDeviceCount">0</span> 个模拟人员设备</div>
                <button class="refresh-btn" onclick="updatePersonnelDevices()">刷新人员设备</button>
            </div>
            <div class="last-update">最后更新时间: <span id="personnelLastUpdateTime">--</span></div>
            <table class="device-table">
                <thead>
                    <tr>
                        <th>设备名称</th>
                        <th>MAC地址</th>
                        <th>信号强度 (RSSI)</th>
                        <th>发射功率 (TX Power)</th>
                        <th>最后发现时间</th>
                    </tr>
                </thead>
                <tbody id="personnelDeviceTableBody">
                    <!-- 设备列表将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
        let updateTimer;
        let lastSmokeUpdate = 0; // 记录上次烟感设备更新的时间戳
        let lastPersonnelUpdate = 0; // 记录上次模拟人员设备更新的时间戳
        let exitAutoModeTimer = 0; // 自动模式退出计时（秒）
        let autoModeTimeout = null;

        // 页面加载时检查用户角色
        document.addEventListener('DOMContentLoaded', function() {
            const userRole = localStorage.getItem('userRole');
            if (userRole === 'admin') {
                document.getElementById('configLink').style.display = 'block';
            }
        });

        // 显示消息
        function showMessage(message, type) {
            const messageElement = document.getElementById('message');
            messageElement.textContent = message;
            messageElement.className = type;
            messageElement.style.display = 'block';
            
            setTimeout(() => {
                messageElement.style.display = 'none';
            }, 3000);
        }

        async function updateStatus() {
            try {
                const response = await fetch('/api/status');
                if (!response.ok) {
                    throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
                }
                
                const data = await response.json();
                //console.log('收到状态数据:', data); // 添加调试日志
                
                // 更新所有状态
                document.getElementById('currentTemp').textContent = data.temperature;
                document.getElementById('currentPower').textContent = data.power;
                document.getElementById('heatingStatus').textContent = data.heating_status || '关闭';
                document.getElementById('coolingStatus').textContent = data.cooling_status || '关闭';
                document.getElementById('workingTime').textContent = `${data.current_working_minutes || 0}`;

                // 更新状态最后更新时间
                updateLastUpdateTime();

                // 更新按钮状态和文本
                updateButtonStates(data.modes, data.heating_status === '开启', data.cooling_status === '开启');
                
                // 更新设备信息
                const now = Date.now();
                if (now - lastSmokeUpdate > 5000) {
                    await updateSmokeDevices();
                    lastSmokeUpdate = now;
                }
                if (now - lastPersonnelUpdate > 3000) {
                    await updatePersonnelDevices();
                    lastPersonnelUpdate = now;
                }
            } catch (error) {
                showMessage('获取状态失败: ' + error.message, 'error');
            }
        }

        // 更新最后更新时间
        function updateLastUpdateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            
            const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            
            const statusLastUpdateTimeElement = document.getElementById('statusLastUpdateTime');
            if (statusLastUpdateTimeElement) {
                statusLastUpdateTimeElement.textContent = formattedTime;
            }
        }

        async function updateSmokeDevices() {
            try {
                const response = await fetch('/api/bluetooth/devices/smoke');
                if (!response.ok) {
                    throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
                }
                
                const data = await response.json();
                
                // 确保data.devices存在且不为null
                if (!data.devices) {
                    data.devices = []; // 设置为空数组以避免错误
                }
                
                // 更新设备计数
                document.getElementById('smokeDeviceCount').textContent = data.devices.length;
                
                // 更新最后更新时间
                const now = new Date();
                document.getElementById('smokeLastUpdateTime').textContent = now.toLocaleString();
                
                // 清空表格
                const tableBody = document.getElementById('smokeDeviceTableBody');
                tableBody.innerHTML = '';
                
                // 填充设备数据
                renderDevices(data.devices, tableBody);
            } catch (error) {
                showMessage('获取烟感设备信息失败: ' + error.message, 'error');
            }
        }

        async function updatePersonnelDevices() {
            try {
                const response = await fetch('/api/bluetooth/devices/personnel');
                if (!response.ok) {
                    throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
                }
                
                const data = await response.json();
                
                // 确保data.devices存在且不为null
                if (!data.devices) {
                    data.devices = []; // 设置为空数组以避免错误
                }
                
                // 更新设备计数
                document.getElementById('personnelDeviceCount').textContent = data.devices.length;
                
                // 更新最后更新时间
                const now = new Date();
                document.getElementById('personnelLastUpdateTime').textContent = now.toLocaleString();
                
                // 清空表格
                const tableBody = document.getElementById('personnelDeviceTableBody');
                tableBody.innerHTML = '';
                
                // 填充设备数据
                renderDevices(data.devices, tableBody);
            } catch (error) {
                showMessage('获取模拟人员设备信息失败: ' + error.message, 'error');
            }
        }

        // 通用的设备渲染函数
        function renderDevices(devices, tableBody) {
            devices.forEach(device => {
                const row = document.createElement('tr');
                
                // 如果是模拟数据，添加特殊样式
                if (device.is_mock) {
                    row.classList.add('mock-device');
                    row.title = '这是模拟数据，不是实际设备';
                }
                
                // 设备名称
                const nameCell = document.createElement('td');
                nameCell.textContent = device.name || '未知设备';
                if (device.is_mock) {
                    nameCell.classList.add('mock-device-name');
                }
                row.appendChild(nameCell);
                
                // MAC地址 - 注意字段名可能是mac或MAC
                const macCell = document.createElement('td');
                macCell.textContent = device.MAC || device.mac || '--';
                row.appendChild(macCell);
                
                // 信号强度 (RSSI) - 注意字段名可能是rssi或RSSI
                const rssiCell = document.createElement('td');
                const rssiValue = document.createElement('div');
                const rssiVal = device.RSSI !== undefined ? device.RSSI : device.rssi;
                rssiValue.textContent = rssiVal !== undefined ? `${rssiVal} dBm` : '--';
                
                // 添加信号强度可视化
                if (rssiVal !== undefined) {
                    const signalStrength = document.createElement('div');
                    signalStrength.className = 'signal-strength';
                    
                    // 计算信号强度百分比 (-30 dBm 是很好的信号, -90 dBm 是很差的信号)
                    const signalPercent = Math.max(0, Math.min(100, (rssiVal + 90) / 60 * 100));
                    
                    const signalBar = document.createElement('div');
                    signalBar.className = 'signal-bar';
                    signalBar.style.width = `${signalPercent}%`;
                    
                    signalStrength.appendChild(signalBar);
                    rssiCell.appendChild(rssiValue);
                    rssiCell.appendChild(signalStrength);
                } else {
                    rssiCell.appendChild(rssiValue);
                }
                row.appendChild(rssiCell);
                
                // 发射功率 (TX Power) - 注意字段名可能是tx_power或TxPower
                const txPowerCell = document.createElement('td');
                const txPowerVal = device.TxPower !== undefined ? device.TxPower : device.tx_power;
                txPowerCell.textContent = txPowerVal !== undefined ? `${txPowerVal} dBm` : '--';
                row.appendChild(txPowerCell);
                
                // 最后发现时间 - 注意字段名可能是last_seen或LastSeen
                const lastSeenCell = document.createElement('td');
                const lastSeenVal = device.LastSeen || device.last_seen;
                if (lastSeenVal) {
                    const lastSeen = new Date(lastSeenVal);
                    lastSeenCell.textContent = lastSeen.toLocaleString();
                } else {
                    lastSeenCell.textContent = '--';
                }
                row.appendChild(lastSeenCell);
                
                tableBody.appendChild(row);
            });
        }

        // 更新按钮状态和文本
        function updateButtonStates(modes, isHeatingActive, isCoolingActive) {
            const autoModeBtn = document.getElementById('autoModeBtn');
            const heatingModeBtn = document.getElementById('forceHeatingMode');
            const coolingModeBtn = document.getElementById('forceCoolingMode');
            
            let isAutoMode = false;
            let isExitingAutoMode = false;
            let isForceHeatingMode = false;
            let isForceCoolingMode = false;
            
            // 检查各种模式状态
            for (const mode of modes) {
                if (mode === '自动模式') {
                    isAutoMode = true;
                } else if (mode === '退出自动模式中') {
                    isExitingAutoMode = true;
                } else if (mode === '强制加热模式') {
                    isForceHeatingMode = true;
                } else if (mode === '强制泵模式') {
                    isForceCoolingMode = true;
                }
            }
            
            // 如果按钮不在等待或错误状态，则更新状态
            if (!autoModeBtn.className.includes('waiting') && !autoModeBtn.className.includes('error')) {
                if (isExitingAutoMode) {
                    autoModeBtn.className = 'mode-button exiting';
                    exitAutoModeTimer++; // 在退出状态下递增计时器
                    autoModeBtn.textContent = `自动模式 [退出中... ${exitAutoModeTimer}秒]`;
                    autoModeBtn.disabled = true;
                    // 在退出过程中禁用其他按钮
                    heatingModeBtn.disabled = true;
                    coolingModeBtn.disabled = true;
                } else if (isAutoMode) {
                    exitAutoModeTimer = 0; // 重置计时器
                    autoModeBtn.className = 'mode-button active';
                    autoModeBtn.textContent = '自动模式 [已开启]';
                    autoModeBtn.disabled = false;
                    // 自动模式开启时禁用其他按钮
                    heatingModeBtn.disabled = true;
                    coolingModeBtn.disabled = true;
                } else {
                    // 检查是否从退出状态转换为停止状态
            if (autoModeBtn.classList.contains('exiting')) {
                        showMessage('自动模式已关闭', 'success');
                        exitAutoModeTimer = 0; // 重置计时器
                    }
                    // 非自动模式状态
                    autoModeBtn.className = 'mode-button';
                    autoModeBtn.textContent = '自动模式 [已停止]';
                    // 只有在强制模式未激活时才启用自动模式按钮
                    autoModeBtn.disabled = isForceHeatingMode || isForceCoolingMode;
                    // 启用其他按钮
                    heatingModeBtn.disabled = false;
                    coolingModeBtn.disabled = false;
                }
            }
            
            // 更新强制加热模式按钮
            if (isForceHeatingMode) {
                heatingModeBtn.className = 'mode-button active';
                heatingModeBtn.textContent = '强制加热 [已开启]';
            } else {
                heatingModeBtn.className = 'mode-button';
                heatingModeBtn.textContent = '强制加热 [已停止]';
            }
            
            // 更新强制冷却模式按钮
            if (isForceCoolingMode) {
                coolingModeBtn.className = 'mode-button active';
                coolingModeBtn.textContent = '强制冷却 [已开启]';
            } else {
                coolingModeBtn.className = 'mode-button';
                coolingModeBtn.textContent = '强制冷却 [已停止]';
            }
        }

        async function stopAutoMode() {
            const autoModeBtn = document.getElementById('autoModeBtn');
            const heatingModeBtn = document.getElementById('forceHeatingMode');
            const coolingModeBtn = document.getElementById('forceCoolingMode');
            
            try {
                const response = await fetch('/api/mode', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        mode: '自动模式',
                        option: 'stop'
                    })
                });
                
                if (response.ok) {
                    // 设置退出状态
                    autoModeBtn.className = 'mode-button exiting';
                    autoModeBtn.disabled = true;
                    heatingModeBtn.disabled = true;
                    coolingModeBtn.disabled = true;
                    exitAutoModeTimer = 0; // 重置计时器
                    autoModeBtn.textContent = '自动模式 [退出中... 0秒]';
                    
                    // 立即更新状态
                    await updateStatus();
                } else {
                    const error = await response.text();
                    autoModeBtn.className = 'mode-button error';
                    autoModeBtn.textContent = '自动模式 [关闭失败]';
                    showMessage(`自动模式关闭失败: ${error}`, 'error');
                    autoModeBtn.disabled = false;
                }
            } catch (error) {
                autoModeBtn.className = 'mode-button error';
                autoModeBtn.textContent = '自动模式 [关闭失败]';
                showMessage('自动模式关闭失败: ' + error.message, 'error');
                autoModeBtn.disabled = false;
            }
        }

        async function switchMode(mode) {
            // 如果当前是退出自动模式中，不允许操作
            const autoModeBtn = document.getElementById('autoModeBtn');
            if (autoModeBtn.classList.contains('exiting')) {
                alert('系统正在退出自动模式，请稍后再试');
                return;
            }
            
            // 获取所有模式按钮
            const heatingModeBtn = document.getElementById('forceHeatingMode');
            const coolingModeBtn = document.getElementById('forceCoolingMode');
            
            // 保存当前按钮文本，以便恢复
            const clickedBtn = document.getElementById(mode === 'auto' ? 'autoModeBtn' : 
                              mode === 'heating' ? 'forceHeatingMode' : 'forceCoolingMode');
            const currentBtnText = clickedBtn.textContent;
            
            // 禁用所有按钮，防止重复点击
            autoModeBtn.disabled = true;
            heatingModeBtn.disabled = true;
            coolingModeBtn.disabled = true;
            
            // 添加加载状态到当前点击的按钮
            clickedBtn.classList.add('loading');
            
            // 设置超时计时器
            const timeoutId = setTimeout(() => {
                // 移除加载状态
                clickedBtn.classList.remove('loading');
                clickedBtn.textContent = currentBtnText;
                
                showMessage('操作超时，请稍后再试', 'error');
                
                // 恢复按钮状态
                autoModeBtn.disabled = false;
                heatingModeBtn.disabled = false;
                coolingModeBtn.disabled = false;
                
                // 重新应用互斥规则
                if (autoModeBtn.classList.contains('active') || autoModeBtn.classList.contains('exiting')) {
                    heatingModeBtn.disabled = true;
                    coolingModeBtn.disabled = true;
                }
                
                // 如果强制加热或强制冷却模式激活，禁用自动模式按钮
                if (heatingModeBtn.classList.contains('active') || coolingModeBtn.classList.contains('active')) {
                    autoModeBtn.disabled = true;
                }
            }, 3000);
            
            try {
                // 模式映射表
                const modeMap = {
                    'auto': '自动模式',
                    'heating': '强制加热模式',
                    'cooling': '强制泵模式'
                };
                
                // 按钮映射表
                const btnMap = {
                    'auto': autoModeBtn,
                    'heating': heatingModeBtn,
                    'cooling': coolingModeBtn
                };
                
                // 确定操作类型
                const option = btnMap[mode].classList.contains('active') ? 'stop' : 'start';
                
                // 发送请求
                //console.log('发送模式请求' + modeMap[mode] + ' ' + option);
                const response = await fetch('/api/mode', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({mode: modeMap[mode], option: option})
                });
                
                if (!response.ok) {
                    throw new Error(`服务器返回错误: ${response.status}`);
                }
                
                // 清除超时计时器
                clearTimeout(timeoutId);
                
                // 立即更新状态
                await updateStatus();
                
                // 操作成功提示
                const modeText = mode === 'auto' ? '自动模式' : 
                               mode === 'heating' ? '强制加热模式' : '强制冷却模式';
                const actionText = option === 'start' ? '启动' : '停止';
                const successMsg = `${modeText}已${actionText}`;
                showMessage(successMsg, 'success');
                
            } catch (error) {
                // 清除超时计时器
                clearTimeout(timeoutId);
                
                // 移除加载状态
                clickedBtn.classList.remove('loading');
                clickedBtn.textContent = currentBtnText;
                showMessage('切换模式失败: ' + error.message, 'error');
                
                // 恢复按钮状态
                autoModeBtn.disabled = false;
                heatingModeBtn.disabled = false;
                coolingModeBtn.disabled = false;
                
                // 重新应用互斥规则
                if (autoModeBtn.classList.contains('active') || autoModeBtn.classList.contains('exiting')) {
                    heatingModeBtn.disabled = true;
                    coolingModeBtn.disabled = true;
                }
                
                // 如果强制加热或强制冷却模式激活，禁用自动模式按钮
                if (heatingModeBtn.classList.contains('active') || coolingModeBtn.classList.contains('active')) {
                    autoModeBtn.disabled = true;
                }
            }
        }

        async function handleAutoMode() {
            const autoModeBtn = document.getElementById('autoModeBtn');
            const isActive = autoModeBtn.classList.contains('active');
            
            if (isActive) {
                await stopAutoMode();
            } else {
                await startAutoMode();
            }
        }

        async function startAutoMode() {
            const autoModeBtn = document.getElementById('autoModeBtn');
            
            // 设置为等待状态
            autoModeBtn.className = 'mode-button waiting';
            autoModeBtn.textContent = '自动模式 [开启中...]';
            autoModeBtn.disabled = true;

            // 设置超时处理
            autoModeTimeout = setTimeout(() => {
                autoModeBtn.className = 'mode-button error';
                autoModeBtn.textContent = '自动模式 [开启失败]';
                autoModeBtn.disabled = false;
                showMessage('自动模式开启超时，请重试', 'error');
            }, 5000); // 5秒超时

            try {
                const response = await fetch('/api/mode', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        mode: '自动模式',
                        option: 'start'
                    })
                });
                
                clearTimeout(autoModeTimeout);
                
                if (response.ok) {
                    autoModeBtn.className = 'mode-button active';
                    autoModeBtn.textContent = '自动模式 [已开启]';
                    showMessage('自动模式已开启', 'success');
                    // 立即更新状态
                    await updateStatus();
                } else {
                    const error = await response.text();
                    autoModeBtn.className = 'mode-button error';
                    autoModeBtn.textContent = '自动模式 [开启失败]';
                    showMessage(`自动模式开启失败: ${error}`, 'error');
                }
            } catch (error) {
                clearTimeout(autoModeTimeout);
                autoModeBtn.className = 'mode-button error';
                autoModeBtn.textContent = '自动模式 [开启失败]';
                showMessage('自动模式开启失败: ' + error.message, 'error');
            } finally {
                autoModeBtn.disabled = false;
            }
        }

        function startUpdates() {
            updateStatus();
            updateTimer = setInterval(updateStatus, 1000);
            
            // 初始加载设备信息
            updateSmokeDevices();
            updatePersonnelDevices();
        }

        function stopUpdates() {
            if (updateTimer) {
                clearInterval(updateTimer);
            }
        }

        // 退出登录
        async function logout() {
            try {
                const response = await fetch('/api/logout', {
                    method: 'POST'
                });
                
                if (response.ok) {
                    window.location.href = '/login.html';
                } else {
                    showMessage('退出失败: ' + (await response.text()), 'error');
                }
            } catch (error) {
                showMessage('退出失败: ' + error.message, 'error');
            }
        }

        // 页面加载时开始更新
        startUpdates();

        // 页面关闭时停止更新
        window.addEventListener('beforeunload', stopUpdates);
    </script>
</body>
</html> 